import redis
from functools import wraps
from scrapy.utils.project import get_project_settings #导入seetings配置

def singleton(cls):
    instances = {}
    @wraps(cls)
    def getinstance(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]
    return getinstance

@singleton
class OPRedis(object):
    def __init__(self):
        settings = get_project_settings()  # 获取settings配置，设置需要的信息
        host = settings['REDIS_HOST']
        port = settings['REDIS_PORT']
        db = settings['REDIS_DB']
        try:
            self.pool = redis.ConnectionPool(host=host, port=port,db=db)
            self.coon = redis.Redis(connection_pool=self.pool)
        except Exception as e:
            print(e)

    #List操作
    def lpush(self,key,value):
        return self.coon.lpush(key, value)

    #Set操作
    # 给name对应的集合中添加元素
    def sadd(self,key,value):
        return self.coon.sadd(key, value)

    # 检查value是否是name对应的集合内的元素
    def sismember(self, key, value):
        return self.coon.sismember(key, value)

    # 删除name对应的集合中的某些值
    def srem(self, key, value):
        return self.coon.srem(key, value)

    # 将某个元素从一个集合中移动到另外一个集合
    def smove(self, src, dst, value):
        return self.coon.smove(src, dst, value)

    #位操作
    def setbit(self, key, offset, value):
        return self.coon.setbit(key, offset, value)

    def getbit(self, key, offset):
        return self.coon.getbit(key, offset)

    #Hash操作
    def hset(self, key, hashkey, value):
        return self.coon.hset(key, hashkey, value)

    def __del__(self):
        self.pool.disconnect()

if __name__ == '__main__':
    global opr
    opr = OPRedis()
    opr.smove('test', 'test11', '11')
    # print(a)